package com.chiffoyqc.utils;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Map;

/**
 * Created by Administrator on 2017/7/7.
 */
public class ReflectUtils {

    /**
     * 获取实例的属性、值，并封装为Map<String,List<String>>
     *     考虑到可能会给很多实例对象生成map，如果在方法中创建map stringBuffer 将会很影响效率，故将之当做参数传入
     */
    public static Map<String, Object> getNameAndValue(Object obj, Map<String, Object> childMap, StringBuffer stringBuffer) throws Exception {
//        Map<String,Object> dataMap = new HashMap<>();
//        List<String> mapList = new ArrayList<>();
//        StringBuffer stringBuffer = new StringBuffer();

        Class<?> clazz = obj.getClass();
        Field[] declaredFields = clazz.getDeclaredFields();
        for (int i = 0, len = declaredFields.length; i < len; i++) {
            String name = declaredFields[i].getName();
            /**将属性名称的首字母改为小写*/
            stringBuffer.append(name.substring(0, 1).toLowerCase());
            stringBuffer.append(name.substring(1));
            String key = stringBuffer.toString();
            stringBuffer.setLength(0);

            /**根据属性名获得属性值*/
            stringBuffer.append("get");
            stringBuffer.append(name);
            String methodName = stringBuffer.toString();
            stringBuffer.setLength(0);
            Method method = clazz.getMethod(methodName);

            Object value = method.invoke(obj);

            /**由每一个实例组成childMap*/
            childMap.put(key, value);

        }

        return childMap;

    }


}
